// 加密数据
export const enciphermentData = function (data) {
  const kvStr = JSON.stringify(data)
  const kv = window.btoa(window.encodeURIComponent(kvStr))
  return kv
}

// 解密数据
export const decryptionData = function (kv) {
  if (kv) {
    try {
      return JSON.parse(window.decodeURIComponent(window.atob(kv)))
    } catch (e) {
      return JSON.parse(kv)
    }
  }
  return null
}

/**
 * 功能：sessionStorage加密存储
 * 【key】string 存值的key键
 * 【data】any 需存的值
 */
export const setSession = (key, data) => {
  const psData = enciphermentData(data)
  sessionStorage.setItem(key, psData)
}

/**
 * 功能：sessionStorage解密取值
 * 【key】string 获取值的key键
 * 返回object或null或string
 */
export const getSession = (key) => {
  const data = sessionStorage.getItem(key)
  if (data) {
    const newData = decryptionData(data)
    return newData
  } else {
    return null
  }
}

/**
 * 功能：localStorage加密存储
 * 【key】string 存值的key键
 * 【data】any 需存的值
 */
export const setStorage = function (key, data) {
  const psData = enciphermentData(data)
  localStorage.setItem(key, psData)
}

/**
 * 功能：localStorage解密取值
 * 【key】string 获取值的key键
 * 返回object或null或string
 */
export const getStorage = function (key) {
  const localData = localStorage.getItem(key)
  if (localData) {
    const newData = decryptionData(localData)
    return newData
  } else {
    return null
  }
}

/*
 * fn [function] 需要防抖的函数
 * delay [number] 毫秒，防抖期限值
 */
export const debounce = (func, time, ctx, immediate) => {
  let timer
  const rtn = (...params) => {
    clearTimeout(timer)
    if (immediate) {
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, time)
      if (callNow) func.apply(ctx, params)
    } else {
      timer = setTimeout(() => {
        func.apply(ctx, params)
      }, time)
    }
  }
  return rtn
}

// 获取浏览器窗口的可视区域的高度
export const getViewPortHeight = () => {
  return document.documentElement.clientHeight || document.body.clientHeight
}
